<template>
  <div class="min-h-screen bg-gradient-to-br from-yellow-50 to-red-50 py-8">
    <div class="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8">
      <div class="flex flex-col lg:flex-row gap-6">
        <main class="flex-1 bg-white p-6 rounded-lg shadow">
          <h1 class="text-2xl font-bold mb-2">手速测试</h1>
          <p class="text-sm text-gray-600 mb-4">在下面区域或按空格键进行两次操作，记录两次操作间隔（ms）。尽量快——最快者会获得火箭图标。</p>

          <div class="mb-4">
            <div
              tabindex="0"
              @click="handleClick"
              @keydown.space.prevent="handleSpace"
              class="select-none cursor-pointer user-select-none h-40 rounded-lg flex flex-col items-center justify-center border-2 border-dashed border-gray-200 hover:border-indigo-300 transition p-4"
            >
              <div v-if="!measured" class="text-center">
                <div class="text-lg font-medium mb-2">准备好了吗？点击两次或按两次空格</div>
                <div class="text-sm text-gray-500">第 {{ clickCount + 1 }} 次</div>
              </div>

              <div v-else class="text-center">
                <div class="text-3xl font-bold mb-1">{{ intervalDisplay }} ms</div>
                <div class="flex items-center justify-center gap-2">
                  <template v-if="isTop">
                    <svg class="w-8 h-8 text-red-500" viewBox="0 0 24 24" fill="none" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 2l3 7 7 .5-5 4 1.5 7L12 17l-8.5 3.5L5 13 0 9.5 7 9l5-7z"/></svg>
                    <div class="text-sm text-green-600">太快了！火箭发射 🚀</div>
                  </template>
                  <template v-else>
                    <svg class="w-6 h-6 text-yellow-500" viewBox="0 0 24 24" fill="none" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v8M8 12h8"/></svg>
                    <div class="text-sm text-gray-600">继续练习，试试更快的手速</div>
                  </template>
                </div>
              </div>
            </div>
          </div>

          <div class="flex items-center gap-3 mb-4">
            <button class="px-4 py-2 bg-indigo-600 text-white rounded" @click="reset">重置</button>
            <div class="flex items-center gap-2">
              <input v-model="name" placeholder="你的名字（用于排行榜，可选）" class="border rounded px-2 py-1" />
              <button :disabled="!measured" class="px-3 py-1 bg-green-500 text-white rounded disabled:opacity-60" @click="submitScore">保存成绩</button>
            </div>
          </div>

          <div class="text-sm text-gray-500">提示：按空格会被捕获为键盘事件，请确保页面获得焦点后再按。</div>
        </main>

        <aside class="w-full lg:w-80 bg-white p-4 rounded-lg shadow max-h-[520px] overflow-hidden">
          <h2 class="text-lg font-semibold mb-3">排行榜（最近 7 天）</h2>
          <div class="text-xs text-gray-500 mb-2">按时间间隔升序（越小越好）。若列表很多可滚动查看。</div>

          <div ref="listEl" class="overflow-y-auto" style="max-height:420px">
            <ul>
              <li v-for="(item, idx) in leaderboard" :key="item.id" class="py-2 px-2 border-b last:border-b-0 flex items-center justify-between">
                <div class="flex items-center gap-3">
                  <div class="w-8 text-center">{{ idx + 1 }}</div>
                  <div>
                    <div class="font-medium">{{ item.name || '匿名' }}</div>
                    <div class="text-xs text-gray-500">{{ new Date(item.ts).toLocaleString() }}</div>
                  </div>
                </div>
                <div class="text-right">
                  <div class="font-semibold">{{ item.interval }} ms</div>
                  <div v-if="idx===0" class="text-xs text-red-500">最快</div>
                </div>
              </li>
            </ul>
            <div v-if="leaderboard.length===0" class="text-center text-gray-400 py-8">暂无成绩，快来挑战！</div>
          </div>
        </aside>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'

const clickCount = ref(0)
const firstTs = ref(null)
const secondTs = ref(null)
const interval = ref(null)
const measured = ref(false)
const name = ref('')
const leaderboard = ref([])
const isTop = ref(false)

const intervalDisplay = computed(() => (interval.value == null ? '--' : interval.value))

const fetchLeaderboard = async (limit = 50) => {
  try {
    const res = await $fetch('/api/hand-speed/list?limit=' + limit)
    if (Array.isArray(res)) {
      leaderboard.value = res.map((r) => ({ ...r }))
    }
  } catch (err) {
    // ignore errors for now
  }
}

const handleClick = () => {
  if (clickCount.value === 0) {
    firstTs.value = Date.now()
    clickCount.value = 1
    measured.value = false
  } else if (clickCount.value === 1) {
    secondTs.value = Date.now()
    interval.value = secondTs.value - firstTs.value
    measured.value = true
    clickCount.value = 2
    updateTopFlag()
  }
}

const handleSpace = (e) => {
  handleClick()
}

const reset = () => {
  clickCount.value = 0
  firstTs.value = null
  secondTs.value = null
  interval.value = null
  measured.value = false
  isTop.value = false
}

const submitScore = async () => {
  if (!measured.value || interval.value == null) return
  try {
    await $fetch('/api/hand-speed/submit', { method: 'POST', body: { name: name.value || '匿名', interval: interval.value } })
    await fetchLeaderboard(50)
    updateTopFlag()
    alert('成绩已保存到排行榜')
  } catch (err) {
    alert('保存失败: ' + String(err))
  }
}

const updateTopFlag = () => {
  const best = leaderboard.value[0]
  if (!best || interval.value == null) {
    isTop.value = true
    return
  }
  isTop.value = interval.value <= Number(best.interval)
}

onMounted(async () => {
  await fetchLeaderboard(50)
  window.addEventListener('keydown', (e) => {
    if (e.code === 'Space') {
      e.preventDefault()
      handleSpace(e)
    }
  })
})

</script>

<style scoped>
/* Minimal styling - layout relies on Tailwind CSS */
</style>
